package com.njtoyo.taxi.admin.service.marketing.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.google.common.collect.Lists;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.library.taxi_service.SkillPrizedService;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivityPrized;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivitySeckillAward;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivitySeckillRecord;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivitySeckillRule;
import com.njtoyo.taxi.admin.mapper.master.enums.ActivityPrizedCategory;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.CreateWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.SeckillListWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.UpdateIsOffineUpdateSeckillWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.UpdateSeckillWrapper;
import com.njtoyo.taxi.admin.service.marketing.SeckillService;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Component
@DS(Const.PRIMARY_DS)
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private ActivityPrizedMapper activityPrizedMapper;

    @Autowired
    private ActivitySeckillRecordMapper activitySeckillRecordMapper;

    @Autowired
    private ActivitySeckillAwardMapper activitySeckillAwardMapper;

    @Autowired
    private ActivitySeckillPrizeMapper activitySeckillPrizeMapper;

    @Autowired
    private ActivitySeckillRuleMapper activitySeckillRuleMapper;

    @Autowired
    private ActivitySeckillWinningPrizeMapper activitySeckillWinningPrizeMapper;

    @Autowired
    private SkillPrizedService skillPrizedService;

    @Override
    public RestResult getList(SeckillListWrapper wrapper) {
        wrapper.setCategory(ActivityPrizedCategory.seckill);
        wrapper.setOrders(Lists.newArrayList(new OrderItem("id", false)));
        IPage<ActivityPrized> res = activityPrizedMapper.selectPage(wrapper);

        return RestResult.success(res);
    }

    @Override
    public RestResult create(CreateWrapper createWrapper) {
        // 校验活动开始、结束时间
        if (createWrapper.getStartedAt().after(createWrapper.getEndedAt())) {
            return RestResult.failed("开始时间必须早于结束时间");
        }

        ActivityPrized insert = CopyUtil.copy(createWrapper, ActivityPrized.class);
        Integer res = activityPrizedMapper.insert(insert);

        return RestResult.success(res);
    }

    @Override
    public RestResult update(Long id, UpdateSeckillWrapper updateSeckillWrapper) {
        // 校验活动是否存在
        QueryWrapper<ActivityPrized> seckillWrapper = new QueryWrapper<>();
        seckillWrapper.eq("category", ActivityPrizedCategory.seckill);
        seckillWrapper.eq("id", id);

        ActivityPrized seckill = activityPrizedMapper.selectOne(seckillWrapper);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 校验活动开始、结束时间
        if (updateSeckillWrapper.getStartedAt().after(updateSeckillWrapper.getEndedAt())) {
            return RestResult.failed("开始时间必须早于结束时间");
        }

        ActivityPrized update = CopyUtil.copy(updateSeckillWrapper, ActivityPrized.class);
        update.setId(id);

        int res = activityPrizedMapper.updateById(update);

        return RestResult.success(res);
    }

    @Override
    public RestResult updateIsOfflineUpdate(Long id, UpdateIsOffineUpdateSeckillWrapper updateIsOffineUpdateSeckillWrapper) {
        // 校验活动是否存在
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, id);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 如果参数为false，则校验1、该活动是否存在奖项；2、该活动是否已配置规则
        if (!updateIsOffineUpdateSeckillWrapper.getIsOfflineUpdate()) {
            QueryWrapper<ActivitySeckillAward> activitySeckillAwardQueryWrapper = new QueryWrapper<>();
            activitySeckillAwardQueryWrapper.eq("activity_id", id);
            activitySeckillAwardQueryWrapper.eq("is_online", true);
            Integer arardNums = activitySeckillAwardMapper.selectCount(activitySeckillAwardQueryWrapper);
            if (arardNums == 0) {
                return RestResult.failed("该活动没有设置线上奖项，请先设置线上奖项");
            }

            QueryWrapper<ActivitySeckillRule> activitySeckillRuleQueryWrapper = new QueryWrapper<>();
            activitySeckillRuleQueryWrapper.eq("activity_id", id);
            Integer ruleNums = activitySeckillRuleMapper.selectCount(activitySeckillRuleQueryWrapper);
            if (ruleNums == 0) {
                return RestResult.failed("该活动没有设置规则，请先设置规则");
            }

            Boolean resetRes = skillPrizedService.resetAward();
            if (!resetRes) {
                return RestResult.failed("活动设置失败，请稍后再试");
            }
        }

        ActivityPrized update = new ActivityPrized();
        update.setId(id);
        update.setIsOfflineUpdate(updateIsOffineUpdateSeckillWrapper.getIsOfflineUpdate());

        int res = activityPrizedMapper.updateById(update);

        return RestResult.success(res);
    }

    @Override
    @Transactional
    public RestResult delete(Long id) {
        QueryWrapper<ActivityPrized> seckillWrapper = new QueryWrapper<>();
        seckillWrapper.eq("category", ActivityPrizedCategory.seckill);
        seckillWrapper.eq("id", id);
        ActivityPrized seckill = activityPrizedMapper.selectOne(seckillWrapper);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        // 判断是否存在活动参与记录
        QueryWrapper<ActivitySeckillRecord> recordWrapper = new QueryWrapper<>();
        recordWrapper.eq("activity_id", id);
        Integer recordCount = activitySeckillRecordMapper.selectCount(recordWrapper);
        if (recordCount > 0) {
            return RestResult.failed("该活动已有用户参与，无法删除");
        }

        // 执行删除
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("activity_id", id);
        activityPrizedMapper.delete(seckillWrapper);
        activitySeckillAwardMapper.delete(wrapper);
        activitySeckillPrizeMapper.delete(wrapper);
        activitySeckillRuleMapper.delete(wrapper);
        activitySeckillRecordMapper.delete(wrapper);
        activitySeckillWinningPrizeMapper.delete(wrapper);

        return RestResult.success();
    }
}
